package interceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mysql.jdbc.StringUtils;

import entity.User;

public class UserLoginInterceptor implements HandlerInterceptor {
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
			Object handler) throws Exception {
		HttpSession session = req.getSession(false);
		String url = req.getRequestURI();
		if (!StringUtils.isNullOrEmpty(url)) {
			if (url.contains("user_login")||url.contains("user_logout")||url.contains("province_list")||url.contains("city_list")) {
				return true;
			}
		}
		boolean validate = false;
		if (session != null) {
			User u = (User) session.getAttribute("LoginUser");
			if (u != null) {
				validate = true;
			}else{
				session.removeAttribute("LoginUser");
			}
		}
		
		if (!validate) {
			ServletOutputStream out = res.getOutputStream();
			out.print(false);
			out.flush();
			out.close();
		}
		
		return validate;
	}

}
